package com.seeqool.v1;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.beans.PropertyVetoException;
import java.sql.SQLException;

import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;

import com.seeqool.v1.datamodel.SQLTable;

public class ResultPanel extends JPanel {

	private static final long serialVersionUID = 1L;
	private JDesktopPane chartDesktop;

	public ResultPanel(String query, SQLTable queryResult) throws HeadlessException, SQLException {
		super();
		setLayout(new BorderLayout());
//		super(JSplitPane.VERTICAL_SPLIT);
		chartDesktop = new JDesktopPane();
		chartDesktop.setPreferredSize(new Dimension(250,250));
		chartDesktop.setBackground(Color.LIGHT_GRAY);
		
		// Build Data Table
		SQLTable dataTable = queryResult;
		JTable dTable=new JTable(dataTable);
		dTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		dTable.setAutoCreateColumnsFromModel(true);
		dTable.setColumnSelectionAllowed(true);
		
		JScrollPane queryScroller = new JScrollPane(new JLabel(" "+query+" "), JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		queryScroller.setMinimumSize  (new Dimension(100, 40));
		queryScroller.setMaximumSize  (new Dimension(5000,40));
		add(queryScroller, BorderLayout.NORTH);
		JScrollPane tableScroller = new JScrollPane(dTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		tableScroller.setPreferredSize(new Dimension(100,100));
		JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, chartDesktop, tableScroller);
		split.setResizeWeight(1);
		add(split, BorderLayout.CENTER);
		chartDesktop.setAutoscrolls(true);
//		setTopComponent(new JScrollPane(chartDesktop));
//		setBottomComponent(infoArea);
//		setResizeWeight(1);
	}
	
	public void addChart(JInternalFrame chart) {
		chart.pack();
		chart.setVisible(true);
		chart.setLocation(chartDesktop.getComponentCount()*20, chartDesktop.getComponentCount()*20);
		chartDesktop.add(chart);
	}
	
	public void arrangeCharts() {
		switch (chartDesktop.getComponentCount()) {
			case 1:
				try {
					((JInternalFrame) chartDesktop.getComponent(0)).setMaximum(true);
				} catch (PropertyVetoException e) {
					e.printStackTrace();
				}
				break;
			case 2:
				int w = chartDesktop.getWidth() / 2;
				int h = chartDesktop.getHeight();
				chartDesktop.getComponent(0).setBounds(new Rectangle(0,0,w,h));
				chartDesktop.getComponent(1).setBounds(new Rectangle(w,0,w,h));
				break;
		}
	}
}
